package br.pro.raphael.airlinerecovery.servlet;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.pro.raphael.air.Airport;
import br.pro.raphael.util.PMF;

@SuppressWarnings("serial")
public class CargaAerodromos extends HttpServlet{	
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		String inicio = req.getParameter("inicio");
		String fim = req.getParameter("fim");
        URL url = new URL("http://raphael.dominiotemporario.com/antrouting/aerodromos.txt");
        BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
        String line;

        List<Airport> aeroportos = new LinkedList();
        

        int count = 0;
        
        while ((line = reader.readLine()) != null) {
        	count++;
        	Airport aerodromo = new Airport();
        	String s[] = line.split(";");
        	
        	aerodromo.setIcao(s[0]);
        	aerodromo.setIata(s[1]);
        	aerodromo.setNome(s[2]);
        	aerodromo.setCidade(s[3]);
        	aerodromo.setUf(s[4]);
        	aerodromo.setLatitude(Double.parseDouble(s[6]));
        	aerodromo.setLongitude(Double.parseDouble(s[8]));
        	if(count>= Integer.parseInt(inicio) && count<= Integer.parseInt(fim)){
        		aeroportos.add(aerodromo);
        	}
        		
        	resp.getWriter().println(line);
        }
        reader.close();
        
    	PersistenceManager pm = PMF.get().getPersistenceManager();
    	pm.makePersistentAll(aeroportos);
    	pm.close();


  		resp.getWriter().println("xxxx");
		
	}

}
